/**
 * 将 base64 转换为 Blob 对象
 * @param {String} data - base64 字符串数据
 * @returns {Blob} Blob 数据
 */
export function base64ToBlob(data) {
  // 正则表达式用于匹配 base64 数据的 MIME 类型
  const rImageType = /data:(image\/.+);base64,/;
  let mimeString = '';
  let raw, i;

  // 从 base64 字符串中提取 MIME 类型
  raw = data.replace(rImageType, (header, imageType) => {
    mimeString = imageType;
    return '';
  });

  // 将 base64 字符串解码为二进制数据
  raw = atob(raw);
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);

  // 将二进制数据填充到 Uint8Array 中
  for (i = 0; i < rawLength; i++) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  // 创建 Blob 对象并返回
  return new Blob([uInt8Array], { type: mimeString });
}

/**
 * 将 URL 转换为 Base64
 * @param {String} url - URL 字符串
 * @param {String} mineType - 图片类型
 * @returns {Promise} Promise 对象，包含 Base64 字符串
 */
export function urlToBase64(url: string, mineType?: string): Promise<string> {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement('CANVAS') as Nullable<HTMLCanvasElement>;
    const ctx = canvas!.getContext('2d');

    const img = new Image();
    img.crossOrigin = '';
    img.onload = function () {
      if (!canvas || !ctx) {
        return reject();
      }
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0);
      const dataURL = canvas.toDataURL(mineType || 'image/png');
      canvas = null;
      resolve(dataURL);
    };
    img.src = url;
  });
}
